package com.github.pig.training.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.github.pig.admin.model.dto.DeptTree;
import com.github.pig.admin.model.dto.UserDTO;
import com.github.pig.admin.model.entity.SysDept;
import com.github.pig.admin.model.entity.SysGroup;
import com.github.pig.admin.model.entity.SysUser;
import com.github.pig.admin.service.SysDeptService;
import com.github.pig.admin.service.SysUserService;
import com.github.pig.common.vo.UserVO;
import com.github.pig.sales.entity.SalesIntentionFlowup;
import com.github.pig.sales.entity.SalesPublicRepertory;
import com.github.pig.sales.service.ISalesFollowUpTeamService;
import com.github.pig.sales.service.ISalesIntentionFlowupService;
import com.github.pig.sales.service.ISalesPublicRepertoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.github.pig.common.constant.CommonConstant;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.common.util.Query;
import com.github.pig.common.util.R;
import com.github.pig.training.entity.TrainingStudent;
import com.github.pig.training.service.ITrainingStudentService;
import com.github.pig.common.web.BaseController;

/**
 * <p>
 * 学员信息 前端控制器
 * </p>
 *
 * @author andrew
 * @since 2018-06-21
 */
@RestController
@RequestMapping("/trainingStudent")
public class TrainingStudentController extends BaseController {
    @Autowired private ITrainingStudentService trainingStudentService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysDeptService deptService;

    @Autowired
    private ISalesFollowUpTeamService teamService;

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return TrainingStudent
    */
    @GetMapping("/{id}")
    public R<TrainingStudent> get(@PathVariable Integer id) {
        return new R<>(trainingStudentService.selectById(id));
    }


    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @RequestMapping("/page")
    public Page page(@RequestParam Map<String, Object> params,UserVO user) {
        Integer userId = userService.findUserByUsername(user.getUsername()).getUserId();
        List<Integer> list = userService.selectSub(userId);
        EntityWrapper wrapper = new EntityWrapper(new TrainingStudent());
        wrapper.where(CommonConstant.DEL_FLAG +"={0}",CommonConstant.STATUS_NORMAL)
//                .and("follow_up_status = {0}","1601")
//                .in("follow_up_user",list)
                .and("follow_up_user = {0}",userId)
                .orderBy("last_follow_up_time",true);
        return trainingStudentService.selectPage(new Query<>(params), wrapper);
    }

    /**
     * 分页查询信息
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @RequestMapping("/studentPage")
    public Page studentPage(@RequestParam Map<String, Object> params,UserVO user) {
        return trainingStudentService.selectPage(new Query<>(params),new EntityWrapper<>());
    }

    /**
     * 分页查询信息
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @RequestMapping("/intentionEntryPage")
    public Page intentionEntryPage(@RequestBody Map<String, Object> params,UserVO user) {
        Integer deptId = userService.findUserByUsername(user.getUsername()).getDeptId();
        List<Integer> list = userService.selectSub(deptId);
        EntityWrapper wrapper = new EntityWrapper(new TrainingStudent());
        wrapper.where(CommonConstant.DEL_FLAG +"={0}",CommonConstant.STATUS_NORMAL)
                .in("collect_user",list).orderBy("last_follow_up_time",true);
        return trainingStudentService.selectPage(new Query<>(params), wrapper);
    }


    /**
     * 条件查询
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @RequestMapping("/searchPage")
    public Page searchPage(@RequestParam Map<String, Object> params,UserVO user) {
        params.put(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        return trainingStudentService.selectPage(new Query<>(params), new EntityWrapper<>());
    }


    /**
     * 添加
     * @param  trainingStudent  实体
     * @return success/false
     */
    @PostMapping
    public R<Boolean> add(@RequestBody TrainingStudent trainingStudent, UserVO user) {
        int userId = userService.findUserByUsername(user.getUsername()).getUserId();
        if (teamService.selectByUserId(userId)){
            trainingStudent.setFollowUpUser(userId);
            trainingStudent.setFollowUpStatus("1601");
            trainingStudent.setCallCount(0);
            trainingStudent.setCurrentCallCount(0);
        }else{
            trainingStudent.setFollowUpStatus("1602");
        }
        trainingStudent.setCollectUser(userId);
        trainingStudent.setCreateUser(userId);
        trainingStudent.setCollectDate(new Date());
        trainingStudent.setCreateTime(new Date());
        trainingStudent.setUpdateTime(new Date());
        trainingStudent.setVersion(0);
        trainingStudent.setDelFlag(CommonConstant.STATUS_NORMAL);
        return new R<>(trainingStudentService.insert(trainingStudent));
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable Integer id) {
        TrainingStudent trainingStudent = new TrainingStudent();
        trainingStudent.setFid(id);
        trainingStudent.setUpdateTime(new Date());
        trainingStudent.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(trainingStudentService.updateById(trainingStudent));
    }

    /**
     * 编辑
     * @param  trainingStudent  实体
     * @return success/false
     */
    @PutMapping
    public R<Boolean> edit(@RequestBody TrainingStudent trainingStudent) {
        trainingStudent.setUpdateTime(new Date());
        return new R<>(trainingStudentService.updateById(trainingStudent));
    }

    /**
     * 跟进
     * 杨北平   2018-06-26
     *
     * @param obj
     * @param user
     * @return
     */
    @PostMapping("/addFlowup")
    public R<Boolean> addFlowup(@RequestBody Object obj,UserVO user){
        return trainingStudentService.addFlowup(obj,user);
    }

    /**
     * 验证手机号、身份证是否已存在
     *  杨北平   2018-06-27
     *
     * @param params
     * @return
     */
    @PostMapping("/checkWeight")
    public R<Boolean> checkWeight(@RequestBody Map<String,Object> params){
        R<Boolean> r = null;
        for (Map.Entry<String,Object> entry : params.entrySet()){
            String entryValue = (entry.getValue().toString()).replace(" ","");
            if (entryValue.equals("")){
                r = new R<>(false);
            }else {
                entry.setValue(entryValue);
                Page page = trainingStudentService.selectPage(new Query<TrainingStudent>(params), new EntityWrapper<>());
                r = new R<>(page.getRecords().size() > 0);
            }
        }
        return r;
    }

    /**
     * 学员批量分组
     * @param fids
     * @return
     */
    @PutMapping("/batchGrouping/{group}")
    public R<Boolean> batchGrouping(@RequestBody Integer[] fids,@PathVariable Integer group,UserVO user){
        int userId = userService.findUserByUsername(user.getUsername()).getUserId();
        List<TrainingStudent> list = new ArrayList<>();
        for(Integer fid : fids){
            TrainingStudent s = new TrainingStudent();
            s.setFid(Integer.valueOf(fid));
            s.setGroupsort(group);
            s.setUpdateTime(new Date());
            s.setUpdateUser(userId);
            list.add(s);
        }
        return new R<>(trainingStudentService.updateBatchById(list));
    }

    /**
     * 验证手机号、身份证是否已存在
     * @param str
     * @return
     */
    @PostMapping("/checkInformation")
    public R<Boolean> checkInformation(@RequestParam(name = "str") String str){
        return trainingStudentService.checkInformation(str);
    }
}
